package com.example.makotoshoda.mycamera3;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicBoolean;


public class MainActivity extends Activity {

    private Camera mCamera = null;
    private CameraPreview mPreview = null;
    private boolean mIsTake = false;
    private boolean mIsShoot = false;

    private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                if (!mIsTake && mCamera != null) {
                    mIsTake = true;
                    mCamera.autoFocus(new Camera.AutoFocusCallback() {
                        @Override
                        public void onAutoFocus(boolean b, Camera camera) {
                            Log.e("focus", String.valueOf(b));
                            mIsShoot = true;
                            mIsTake = false;
                        }
                    });
//                        mCamera.takePicture(null, null, mPicJpgCallback);
                }
            }
            return false;
        }
    };
    private View.OnClickListener shoot = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!mIsTake && mCamera != null) {
                mIsTake = true;
                mCamera.autoFocus(new Camera.AutoFocusCallback() {
                    @Override
                    public void onAutoFocus(boolean b, Camera camera) {
                        mIsShoot = true;
                        mIsTake = false;
                    }
                });
            }
        }
    };

    // 画像ビューアに出るように登録する
    private void registAndroidDB(String imgPath) {

        ContentValues values = new ContentValues();
        ContentResolver contentResolver = MainActivity.this.getContentResolver();

        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put("_data", imgPath);

        contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }
    // プレビューコールバック
    private Camera.PreviewCallback mPreviewCallback = new Camera.PreviewCallback() {
        public void onPreviewFrame(byte[] bytes, Camera camera) {
            if (mIsShoot) {
                Log.e("mylog", "preview");
                mIsShoot = false;

//                    mCamera.stopPreview();
                int height = camera.getParameters().getPreviewSize().height;
                int width = camera.getParameters().getPreviewSize().width;
                if (camera.getParameters().getPreviewFormat() == ImageFormat.NV21) {
                    YuvImage yimg = new YuvImage(bytes, ImageFormat.NV21,
                            width, height, null);

                    String imgPath = getFilePath();
                    Log.e("mylog", imgPath);

                    FileOutputStream fos;
                    try {
                        fos = new FileOutputStream(imgPath);
                        yimg.compressToJpeg(new Rect(0,0,width, height),
                                100, fos);
                        //bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fos = null;

                }
                Log.e("mylog", "start preview");
                camera.startPreview();
            }
        }
    };

    // 保存ファイルのパスを取得する
    private String getFilePath() {
        String saveDir = Environment.getExternalStorageDirectory() + "/mytest";

        File file = new File(saveDir);
        if (!file.exists()) {
            if (!file.mkdir()) {
                Log.e("Debug", "Make Dir Error");
            }
        }

        // 保存
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return saveDir + "/" + sf.format(cal.getTime()) + ".jpg";
    }

    // 画像ow保存する
    private void saveBitmap(Bitmap bmp) {
        String imgPath = getFilePath();

        FileOutputStream fos;
        try {
            fos = new FileOutputStream(imgPath);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        fos = null;
    }

    // 起動時
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("mylog", "Create");
        setContentView(R.layout.activity_main);

        // プレビュー用アクティビティをを設定する
        mPreview = new CameraPreview(this);

        FrameLayout frame = (FrameLayout)findViewById(R.id.frame);
        frame.addView(mPreview, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        Log.e("mylog", "start preview");

        mPreview.setOnTouchListener(mTouchListener);

        Button btn = (Button) findViewById(R.id.shoot);
        btn.setOnClickListener(shoot);


    }
    // ?
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    // ?
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e("mylog", "start");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e("mylog", "restart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("mylog", "resume");

        // カメラの作成
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
            this.finish();
        }
        mPreview.setCamera(mCamera);
        mCamera.startPreview();
        mCamera.setPreviewCallback(mPreviewCallback);
    }

    // ポーズ
    @Override
    protected void onPause() {
        super.onPause();
        Log.e("mylog", "Pause");
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mPreview.release();
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e("mylog", "stop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("mylog", "destroy");
    }

    @Override
    public void finish() {
        super.finish();
        Log.e("mylog", "finish");
    }
}
